package com.zz.framework.core.http

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.URL

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/18 09:36.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
object NetStatusUtils {
    suspend fun getPing(host: String = "www.baidu.com"): Long? {
        return withContext(Dispatchers.IO) {
            try {
                val process = ProcessBuilder()
                    .command("/system/bin/ping", "-c", "3", host)
                    .redirectErrorStream(true)
                    .start()

                val reader = process.inputStream.bufferedReader()
                val output = reader.readText()
                process.waitFor()

                // 提取平均延迟时间
                val timeMatch = Regex("avg = ([0-9.]+)").find(output)
                timeMatch?.groupValues?.get(1)?.toLongOrNull()
            } catch (e: Exception) {
                null
            }
        }
    }

    suspend fun measureDownloadSpeed(url: String = "https://speed.hetzner.de/100MB.bin"): Double {
        return withContext(Dispatchers.IO) {
            try {
                val startTime = System.currentTimeMillis()
                val connection = URL(url).openConnection() as HttpURLConnection
                connection.connectTimeout = 5000
                connection.readTimeout = 5000
                connection.connect()

                val inputStream = connection.inputStream
                val buffer = ByteArray(1024)
                var bytesRead: Int
                var totalBytes = 0L

                while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                    totalBytes += bytesRead
                }

                val endTime = System.currentTimeMillis()
                val speed = (totalBytes * 8) / (endTime - startTime) // 单位：kbps
                speed / 1024.0 // 转换为 Mbps
            } catch (e: Exception) {
                0.0
            }
        }
    }

    suspend fun checkNetworkQuality(): String {
        val latency = getPing() ?: return "无法连接网络"
        val downloadSpeed = measureDownloadSpeed()
        return when {
            latency < 50 && downloadSpeed > 10 -> "网络流畅"
            latency < 100 && downloadSpeed > 5 -> "网络一般"
            else -> "网络较差"
        }
    }


    suspend fun isInternetAccessible( url: String = "https://www.baidu.com/"): Boolean {
        return withContext(Dispatchers.IO) {
            try {
                val url = URL(url)
                val connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 3000
                connection.connect()
                connection.responseCode == 200
            } catch (e: Exception) {
                false
            }
        }
    }
}